package com.xss.ipctest.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * 对数据表进行增删改查
 * 除onCreate方法外，其他方法均运行在Binder线程池
 */
public class BookProvider extends ContentProvider {
    private static final String TAG = "BookProvider";

    public static final String AUTHORITY = "com.xss.ipctest.book.provider";
    //为book,user表指定URI
    public static final Uri BOOK_CONTENT_URI = Uri.parse(
            "content://" + AUTHORITY + "/book"
    );
    public static final Uri USER_CONTENT_URI = Uri.parse(
            "content://" + AUTHORITY + "/user"
    );
    public static final int BOOK_URI_CODE = 0;
    public static final int USER_URI_CODE = 1;
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    //URI关联uri_code
    static {
        sUriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE);
        sUriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE);
    }

    private Context mContext;
    private SQLiteDatabase mDb;

    /**
     * ContentProvider创建，做初始化操作
     *
     * @return
     */
    @Override
    public boolean onCreate() {
        Log.i(TAG, "onCreate: 当前线程：" + Thread.currentThread().getName());
        mContext = getContext();
        initProviderData();
        return true;
    }

    private void initProviderData() {
        mDb = new DbOpenHelper(mContext).getWritableDatabase();
        mDb.execSQL("delete from " + DbOpenHelper.BOOK_TABLE_NAME);
        mDb.execSQL("delete from " + DbOpenHelper.USER_TABLE_NAME);
        mDb.execSQL("insert into book values(3,'Android');");
        mDb.execSQL("insert into book values(4,'Ios');");
        mDb.execSQL("insert into book values(5,'Html5');");
        mDb.execSQL("insert into user values(1,'jake',1);");
        mDb.execSQL("insert into user values(2,'jasmine',0);");
    }

    /**
     * 查
     *
     * @param uri
     * @param projection
     * @param selection
     * @param selectionArgs
     * @param sortOrder
     * @return
     */
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.i(TAG, "query: 当前线程：" + Thread.currentThread().getName());
        String tableName = getTableName(uri);
        if (tableName == null) try {
            throw new IllegalAccessException("Unsupported URI:" + uri);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return mDb.query(tableName, projection, selection, selectionArgs,
                null, null, sortOrder, null);
    }

    /**
     * @param uri
     * @return 返回uri请求对应的MIME类型
     */
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.i(TAG, "getType: ");
        return null;
    }

    /**
     * 增
     *
     * @param uri
     * @param values
     * @return
     */
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Log.i(TAG, "insert: ");
        String tableName = getTableName(uri);
        if (tableName == null)
            try {
                throw new IllegalAccessException("Unsupported URI:" + uri);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        mDb.insert(tableName, null, values);
        mContext.getContentResolver().notifyChange(uri, null);
        return uri;
    }

    /**
     * 删
     *
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.i(TAG, "delete: ");
        if (getTableName(uri) == null)
            try {
                throw new IllegalAccessException("Unsupported URI:" + uri);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        int count = mDb.delete(getTableName(uri), selection, selectionArgs);
        if (count > 0) {
            mContext.getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    /**
     * 改
     *
     * @param uri
     * @param values
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.i(TAG, "update: ");
        String tableName = getTableName(uri);
        if (tableName == null)
            try {
                throw new IllegalAccessException("Unsupported URI:" + uri);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        int row = mDb.update(tableName, values, selection, selectionArgs);
        if (row > 0) {
            mContext.getContentResolver().notifyChange(uri, null);
        }
        return row;
    }

    /**
     * 根据URI获取Uri_code，返回对应表名
     *
     * @param uri
     * @return
     */
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (sUriMatcher.match(uri)) {
            case BOOK_URI_CODE:
                tableName = DbOpenHelper.BOOK_TABLE_NAME;
                break;
            case USER_URI_CODE:
                tableName = DbOpenHelper.USER_TABLE_NAME;
                break;
            default:
                break;
        }
        return tableName;
    }
}
